Page({
  data: {
    currentPage: 1,
    pageSize: 8,
    orderName: '',
    time: 1,
    state: 0,
    orderList: [],
    isRefreshing: false,
    userId: null,
    hasMore: true,
    qrCodeUrl: ''
  },

  onLoad() {
    // 获取用户信息
    wx.getStorage({
      key: "userInfo",
      success: (res) => {
        this.setData({
          userId: res.data.id
        }, () => {
          // 获取到用户ID后立即加载订单列表
          this.handleFindOrderByState();
        });
      }
    });
  },

  // 处理搜索输入
  handleSearch(e) {
    this.setData({
      orderName: e.detail.value,
      currentPage: 1  // 搜索时重置页码
    }, () => {
      this.handleFindOrderByState();
    });
  },

  handleFindOrderByState() {
    if (!this.data.userId) return;
    
    wx.request({
      url: `http://localhost:9301/order/findOrderByState`,
      method: "post",
      data: {
        currentPage: this.data.currentPage,
        pageSize: this.data.pageSize,
        orderName: this.data.orderName,
        time: this.data.time,
        state: this.data.state,
        userId: this.data.userId
      },
      success: (res) => {
        console.log("订单信息", res.data);
        if (res.data.rows) {
          const newList = res.data.rows || [];
          this.setData({
            orderList: this.data.currentPage === 1 ? newList : [...this.data.orderList, ...newList],
            hasMore: newList.length === this.data.pageSize,
            isRefreshing: false
          });
        }
      },
      fail: (err) => {
        console.error("查询失败", err);
        this.setData({
          isRefreshing: false
        });
      }
    });
  },

  // 刷新
  onRefresh() {
    this.setData({
      isRefreshing: true,
      currentPage: 1
    }, () => {
      this.handleFindOrderByState();
    });
  },

  // 加载更多
  loadMore() {
    if (!this.data.hasMore) {
      return;
    }
    
    this.setData({
      currentPage: this.data.currentPage + 1
    }, () => {
      this.handleFindOrderByState();
    });
  },

  
  handleGoToOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
    });
  }
});
